import React, { FC, useEffect } from "react";
import cls from "@/components/App/App.module.scss";
import { Navigate, Outlet, useLocation } from "react-router-dom";
import "@/styles/base.scss";
import { Sidebar } from "@/feature/Sidebar/Sidebar";
import { useToken, useUserMe } from "@/store/auth";
import cn from "classnames";
import { getUser, getUserMe, useUsers } from "@/api/users";
import { Header } from "@/feature/Header/Header";

export const App: FC = () => {
  const { pathname } = useLocation();
  const showSidebar = pathname !== "/login";
  const { credentials } = useToken();
  const { userMe, setUser } = useUserMe();

  useEffect(() => {
    if (!userMe && showSidebar) {
      getUserMe().then((res) => setUser(res));
    }
  }, [userMe, showSidebar]);

  return (
    <div className="page-container">
      {showSidebar && <Sidebar />}
      <div className={cn(cls.container, { [cls.showSidebar]: showSidebar })}>
        {showSidebar && <Header />}
        {showSidebar && !credentials && <Navigate to="/login" replace />}
        <Outlet />
      </div>
    </div>
  );
};
